package com.infore.photobrowseselect;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.infore.photobrowseselect.matisse.Matisse;
import com.infore.photobrowseselect.matisse.MimeType;
import com.infore.photobrowseselect.matisse.engine.impl.GlideEngine;
import com.infore.photobrowseselect.matisse.internal.entity.CaptureStrategy;
import com.infore.photobrowseselect.matisse.internal.ui.widget.MediaGridInset;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import static android.app.Activity.RESULT_OK;

/**
 * 选择图片 Fragment
 *
 * @author dingxinlin
 * @date 2018-4-20
 */
public class SelectPhotoFragment extends Fragment {

    public static final String EXTRA_MAX_SELECTABLE = "EXTRA_MAX_SELECTABLE";
    public static final String EXTRA_SPAN_COUNT = "EXTRA_SPAN_COUNT";

    private static final int REQUEST_CODE_CHOOSE = 520;

    private int maxSelectable = 9;
    private int spanCount = 3;

    private RecyclerView mRecyclerView;
    private SelectPhotoAdapter mAdapter;
    private List<String> mSelected = new ArrayList<>();

    public static SelectPhotoFragment newInstance(int maxSelectable, int spanCount) {
        SelectPhotoFragment fragment = new SelectPhotoFragment();
        Bundle args = new Bundle();
        args.putInt(EXTRA_MAX_SELECTABLE, maxSelectable);
        args.putInt(EXTRA_SPAN_COUNT, spanCount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_browser_photo, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRecyclerView = view.findViewById(R.id.recycler_view);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // 接收外部传入参数
        Bundle bundle = getArguments();
        int extraMaxSelectable = bundle.getInt(EXTRA_MAX_SELECTABLE);
        int extraSpanCount = bundle.getInt(EXTRA_SPAN_COUNT);
        if (extraMaxSelectable > 0) {
            this.maxSelectable = extraMaxSelectable;
        }
        if (extraSpanCount > 0) {
            this.spanCount = extraSpanCount;
        }

        mAdapter = new SelectPhotoAdapter();
        mRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), spanCount));
        int spacing = getResources().getDimensionPixelSize(R.dimen.photo_grid_spacing);
        mRecyclerView.addItemDecoration(new MediaGridInset(spanCount, spacing, false));
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.getItemAnimator().setRemoveDuration(300);
        mRecyclerView.setNestedScrollingEnabled(false);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            List<String> selectedImg = Matisse.obtainPathResult(data);
            mSelected.addAll(selectedImg);
            // 移除Uri相同的图片
            removeDuplicate(mSelected);
            mAdapter.notifyDataSetChanged();

            for (String path : selectedImg) {
                Log.d("dxl", path);
            }
        }
    }

    /**
     * 移除list中相同的元素
     *
     * @param list
     * @return
     */
    public List<String> removeDuplicate(List<String> list) {
        Set set = new LinkedHashSet<>();
        set.addAll(list);
        list.clear();
        list.addAll(set);
        return list;
    }

    /**
     * 外部获取已选照片
     * @return
     */
    public List<String> getSelectedPhotos() {
        return mSelected;
    }


    /**
     * 适配器
     */
    private class SelectPhotoAdapter extends RecyclerView.Adapter<SelectPhotoAdapter.ViewHolder> {

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_browser_photo, parent, false);
            ViewHolder vh = new ViewHolder(view);
            return vh;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, final int position) {
            if (position != mSelected.size()) {
                holder.delete.setVisibility(View.VISIBLE);
                Glide.with(holder.imageView.getContext())
                        .load(mSelected.get(position))
                        .placeholder(R.drawable.image_loading)
                        .error(R.drawable.image_fail)
                        .centerCrop()
                        .into(holder.imageView);
            } else {
                // 后一个item特殊处理
                holder.imageView.setImageResource(R.drawable.ic_add_image);
                holder.delete.setVisibility(View.GONE);
            }

            /**
             * 新增按钮监听
             */
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (position != mSelected.size()) {
                        return;
                    }

                    if (mSelected.size() >= maxSelectable) {
                        Toast.makeText(getContext(),
                                getContext().getString(R.string.hint_most_select, maxSelectable),
                                Toast.LENGTH_SHORT)
                                .show();
                        return;
                    }

                    Matisse.from(SelectPhotoFragment.this)
                            .choose(MimeType.ofAll(), false)
                            .countable(true)
                            .capture(true)
                            .captureStrategy(new CaptureStrategy(
                                    // TODO: 2018-4-24 此处修改为项目包名，manifest文件中也要修改
                                    true, "com.infore.photobrowseselect.fileprovider"))
                            .maxSelectable(maxSelectable - mSelected.size())
                            .spanCount(spanCount)
                            .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                            .thumbnailScale(0.85f)
                            .imageEngine(new GlideEngine())
                            .forResult(REQUEST_CODE_CHOOSE);
                }
            });

            /**
             * 删除按钮监听
             */
            holder.delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // 从数据源中移除
                    mSelected.remove(position);
                    // 刷新被移除的地方
                    mAdapter.notifyItemRemoved(position);
                    // 刷新被移除的数据，以及其后面的数据
                    mAdapter.notifyItemRangeChanged(position, mAdapter.getItemCount());
                }
            });
        }

        @Override
        public int getItemCount() {
            return mSelected.size() + 1;
        }

        /**
         * View Holder
         */
        class ViewHolder extends RecyclerView.ViewHolder {
            ImageView imageView;
            ImageView delete;

            public ViewHolder(View itemView) {
                super(itemView);
                imageView = itemView.findViewById(R.id.image_view);
                delete = itemView.findViewById(R.id.delete_btn);
            }
        }
    }
}
